//
//  DLContentnVC.m
//  IntegralDog
//
//  Created by User on 16/1/25.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "DLContentnVC.h"
#import "AppDelegate.h"
#import "Macro.h"
#import "PersonalNetTool.h"
#import "ProductModel.h"
#import "UIImageView+WebCache.h"

@interface DLContentnVC ()

@end
CGFloat _width;

ProductModel *model;
UIImageView *img;
UILabel *appName;
UILabel *content;
UILabel *typeLab;
UILabel *DownCount;
UILabel *jifen;
NSString *Url;
NSString *AppName;
@implementation DLContentnVC

- (void)viewWillAppear:(BOOL)animated
{
    [self addObserver:self forKeyPath:@"pid" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}
- (void)viewDidAppear:(BOOL)animated
{
    int Id = (int)[[self valueForKey:@"pid"] integerValue]; //NSLog(@"%d",Id);
    [PersonalNetTool getProductDetailsWithpid:Id complationBlock:^(NSDictionary *dic) {
        model = [[ProductModel alloc] initWithDictionary:[dic objectForKey:@"product"]];
        appName.text = model.title;
        content.text = model.remark;
        typeLab.text = model.classify;
        DownCount.text = [NSString stringWithFormat:@"%ld",[model.downloadUsed integerValue]];
        jifen.text = [NSString stringWithFormat:@"%ld",[model.reward integerValue]];
        [img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGEURL,model.logo]] placeholderImage:[UIImage imageNamed:@"Icon－60@3X"]];
        for (int i = 0; i < 5; i ++) {
            UIImageView *xing = [[UIImageView alloc] initWithFrame:CGRectMake1(120+9*i , 115, 8, 8)];
            xing.image = [UIImage imageNamed:@"Btn_Normal_Xingxingb.png"];
            xing.tag = i;
            if (xing.tag < (int)[model.starClass integerValue]) {
                xing.image = [UIImage imageNamed:@"Btn_Normal_Xingxinga.png"];
            }
            [self.view addSubview:xing];
        }
        img.layer.cornerRadius = 20;
        img.layer.masksToBounds = YES;
        Url = model.DownloadUrl;
        AppName = model.title;
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _width = [[[NSUserDefaults standardUserDefaults] objectForKey:@"width"] floatValue];
    self.title = @"应用下载";
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 12, 22);
    
    [backBtn setImage:[UIImage imageNamed:@"Btn_Nourmal_Jiantou"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"Btn_Push_Jiantou"] forState:UIControlStateSelected];
    [backBtn addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    img = [[UIImageView alloc] initWithFrame:CGRectMake1(20, 65, 90, 90)];
    img.layer.cornerRadius = 10;
    [self.view addSubview:img];
   
    [self addcontent];
}

- (void)downloadFileWithOption:(NSDictionary *)paramDic
                 withInferface:(NSString*)requestURL
                     savedPath:(NSString*)savedPath
               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      progress:(void (^)(float progress))progress

{
    
    //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURL parameters:paramDic error:nil];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
//    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//        float p = (float)totalBytesRead / totalBytesExpectedToRead;
//        progress(p);
//        NSLog(@"download：%f", (float)totalBytesRead / totalBytesExpectedToRead);
//        
//    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation,responseObject);
        NSLog(@"下载成功");
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        success(operation,error);
        
        NSLog(@"下载失败");
        
    }];
    
    [operation start];
}
//下载
- (void)downloadTouched:(UIButton *)sender
{
    NSLog(@"ddddddddddd    %@",Url);    
    [[UIApplication sharedApplication] openURL: [ NSURL URLWithString:model.DownloadUrl]];
    
    int Id = (int)[[self valueForKey:@"pid"] integerValue];
    NSDictionary *dic =@{@"token":TOKEN,@"uid":@(UID),@"pid":@(Id)};
    [DataTool postWithUrl:ADD_DOWNLOAD_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = IntegrationJsonParserWithData(data);
        int code = [[jsonDic objectForKey:@"code"] intValue];
        if (code == 100) {
            NSLog(@"下载成功");
        }else{
            NSLog(@"下载失败");
        }
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];

}

- (void)addcontent
{
    
    appName = [[UILabel alloc] initWithFrame:CGRectMake2(120, 60, 150, 30)];
    appName.tag = 0;
    UIButton *downloadButt = [[UIButton alloc] initWithFrame:CGRectMake2(275, 123, 35, 16)];
    [downloadButt setImage:[UIImage imageNamed:@"Btn_Normal_Xiazai"] forState:UIControlStateNormal];
    [downloadButt
     addTarget:self action:@selector(downloadTouched:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appName];
    [self.view addSubview:downloadButt];
    
    UILabel *xianlab = [[UILabel alloc] initWithFrame:CGRectMake2(20, 160, 300, 0.5)];
    xianlab.backgroundColor = fontLightGrayColor2;
    xianlab.alpha = 0.5;
    [self.view addSubview:xianlab];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake2(20, 170, 100, 30)];
    label.text = @"下载说明:";
    label.tag = 6;
    UILabel *wanchenglabel = [[UILabel alloc] initWithFrame:CGRectMake2(120, 117, 60, 30)];
    wanchenglabel.text = @"完成下载";
    wanchenglabel.tag = 1;
    wanchenglabel.textColor = fontLightGrayColor;
    UILabel *jianglilabel = [[UILabel alloc] initWithFrame:CGRectMake2(170, 117, 60, 30)];
    jianglilabel.text = @"奖励";
    jianglilabel.tag = 2;
    [label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    
    content = [[UILabel alloc] initWithFrame:CGRectMake2(20, 175, 280, 120)];
    content.numberOfLines = 0;
    content.textColor = fontLightGrayColor;
    content.tag = 7;
    [self.view addSubview:content];
    [self.view addSubview:label];
    
    typeLab = [[UILabel alloc] initWithFrame:CGRectMake2(120, 80, 100, 20)];
    typeLab.tag = 3;
    UILabel *DownCount = [[UILabel alloc] initWithFrame:CGRectMake2(165, 112, 100, 14)];
    DownCount.tag = 4;
    UIImageView *moneyPic = [[UIImageView alloc] initWithFrame:CGRectMake2(200, 126, 12, 12)];
    moneyPic.image = [UIImage imageNamed:@"Btn_Normal_money"];
    jifen = [[UILabel alloc] initWithFrame:CGRectMake2(215, 123, 40, 16)];
    jifen.tag = 5;
    jifen.textColor = lightOrangeColor;
    DownCount.textColor = fontLightGrayColor;
    typeLab.textColor = fontLightGrayColor;

    [self setFontLabel:wanchenglabel byscale:_width];
    [self setFontLabel:jianglilabel byscale:_width];
    [self setFontLabel:appName byscale:_width];
    [self setFontLabel:typeLab byscale:_width];
    [self setFontLabel:DownCount byscale:_width];
    [self setFontLabel:jifen byscale:_width];
    [self setFontLabel:content byscale:_width];
    
    [self.view addSubview:wanchenglabel];
    [self.view addSubview:jianglilabel];
    [self.view addSubview:typeLab];
    [self.view addSubview:DownCount];
    [self.view addSubview:jifen];
    [self.view addSubview:moneyPic];
    
}

- (void)setFontLabel:(UILabel *)label  byscale:(CGFloat )width
{
    int size;
    if (width == 1) {
        size = 14;
    }
    else  if (width >1&&width <1.29) {
        size = 16;
    }
    else
    {
        size = 18;
    }
    if (label.tag == 0) {
        [label setFont:[UIFont systemFontOfSize:size]];
        
    }
    else
    {
        [label setFont:[UIFont systemFontOfSize:size-4]];
    }
}

- (void)doBack:(UIButton *)butt
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = NO;
    [self removeObserver:self forKeyPath:@"pid"];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

CG_INLINE CGRect
CGRectMake1(CGFloat x,CGFloat y,CGFloat width,CGFloat height)
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    return CGRectMake(x * app.autoSizeScaleX, y * app.autoSizeScaleY, width * app.autoSizeScaleX, height * app.autoSizeScaleX);
}
CG_INLINE CGRect
CGRectMake2(CGFloat x,CGFloat y,CGFloat width,CGFloat height)
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    return CGRectMake(x * app.autoSizeScaleX, y * app.autoSizeScaleY, width * app.autoSizeScaleX, height * app.autoSizeScaleY);
}


@end
